package cn.ronghuanet.base.controller;

import cn.ronghuanet.base.dto.RegisterSendSmsDTO;
import cn.ronghuanet.base.service.IVerifyCodeService;
import cn.ronghuanet.base.util.AjaxResult;
import cn.ronghuanet.base.util.StrUtils;
import cn.ronghuanet.base.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/verifyCode")
public class VerifyCodeController {

    @Autowired
    private IVerifyCodeService verifyCodeService;

    // 前后端不分离获取图片验证码的
/*    @GetMapping("/image")
    public void image(HttpSession session, HttpServletResponse response) throws IOException {
        // 1 获取4位数/6位数的随机字符串
        String randomStr = StrUtils.getComplexRandomString(4);
        System.out.println(randomStr);

        // 只有多次session的id一致,他们才是同一个会话请求
        //session.getId()

        // 2 将字符串放入session中,在后续做注册的时候,要从session 中获取随机字符串与前端用户输入的想比对
        session.setAttribute("register_image_verifyCode",randomStr);

        // 3 根据字符串得到一个图片&以流的形式将图片返回给前端
        ServletOutputStream os = response.getOutputStream();
        VerifyCodeUtils.outputImage(200,40,os,randomStr);
    }*/

    /**
     * 注册页面获取图片验证码
     * @return
     */
    @GetMapping("/image/{imageCodeKey}")
    public AjaxResult getImageCodeByRegister(@PathVariable("imageCodeKey")String imageCodeKey,HttpSession session) throws IOException {
        System.out.println("sessionId------------>"+session.getId());
        String base64Str = verifyCodeService.getImageCodeByRegister(imageCodeKey);
        return AjaxResult.success(base64Str);
    }

    @PostMapping("/sms/register")
    public AjaxResult registerSendSms(@RequestBody RegisterSendSmsDTO dto){
        verifyCodeService.registerSendSms(dto);
        return AjaxResult.success();
    }

    @PostMapping("/sms/bind")
    public AjaxResult bindSendSms(@RequestBody Map<String,String> map){
        verifyCodeService.bindSendSms(map);
        return AjaxResult.success();
    }
}
